<template>
  <div class="app-container">
    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" :close-on-click-modal="false" append-to-body @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="名称" prop="basicName" >
          <el-input v-model="form.basicName" placeholder="请输入名称" style="width: 80%;"/>
        </el-form-item>
        <el-form-item label="字段类型" prop="dataExtend" v-if="false">
          <el-select v-model="form.dataExtend" placeholder="请选择字段类型" style="width: 80%;">
            <el-option
              v-for="dict in dict.type.data_extend"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select><br /><font style="color: red">&nbsp;*复杂属性：子表；虚字段：显示逻辑分类</font>
        </el-form-item>
        <el-form-item label="属性分类" prop="attributeType">
          <el-select v-model="form.attributeType" placeholder="请选择属性类别" style="width: 80%;">
            <el-option
              v-for="dict in dict.type.field_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="代码" prop="basicCode">
          <el-input v-if="form.basicCode == '_RESPONUSERNAME' || form.basicCode == '_EXECUTORNAME' || form.basicCode == '_CHECKUSERNAME' || form.basicCode == '_RESPONDEPTNAME'" readonly maxlength="40" v-model="form.basicCode" placeholder="请输入代码" style="width: 80%;"/>
          <el-input v-else maxlength="40" v-model="form.basicCode" placeholder="请输入代码" style="width: 80%;"/>
          <br/><font style="color: red">&nbsp;*数据通过模型转换时代码后缀相同属性可以匹配填充值。（例如：_b和a_b可以匹配）</font>
        </el-form-item>
        <el-form-item label="数据类型" v-if="form.formTypeName !== 'datalist'">
          <el-select v-model="form.basicJavaType" placeholder="" style="width: 80%;">
            <el-option
              key=""
              label="请选择数据类型"
              value=""
            ></el-option>
            <el-option
              v-for="dict in dict.type.basic_java_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="字典" v-if="form.formTypeName !== 'datalist' && form.basicJavaType != 'int'
        && form.basicJavaType != 'double' && form.parentLinkageId ==''">
          <el-select v-model="form.formDictType" style="width: 80%;">
            <el-option
              key=""
              label="请选择"
              value=""
            ></el-option>
            <el-option
              v-for="dict in dictList"
              :key="dict.dictType"
              :label="dict.dictName"
              :value="dict.dictType"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联动父级字段" v-if="form.parentLinkageId != '' || form.formDictType == ''">
          <el-select v-model="form.parentLinkageId" style="width: 80%;">
            <el-option
              key=""
              label="请选择"
              value=""
            ></el-option>
            <el-option
              v-for="sl in selectList"
              :key="sl.id"
              :label="sl.basicName"
              :value="sl.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="表单元素类型">
          <el-select v-model="form.formTypeName" placeholder="请选择表单元素类型" style="width: 80%;"  @change="chDataExtend(form.formTypeName)">
            <el-option
              v-for="dict in dict.type.form_type_name"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="函数公式" v-if="this.form.formTypeName === 'formula'"  >
          <el-select key="drawTypeId" v-model="form.drawTypeId" placeholder="请选择" style="width: 80%;"  clearable @change="chFormulaData(form.id,form.drawTypeId)">
            <el-option
              v-for="draw in formulaList"
              :key="draw.id"
              :label="draw.name"
              :value="draw.id"
            ></el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="" v-if="this.form.formTypeName === 'formula' && this.form.drawTypeId != null
        && this.form.drawTypeId !== '' && this.form.drawTypeId !== undefined">
          <div  v-for="(data, index) in this.formulaArgumentData" >
            <span >{{ data.name }}：</span>
            <el-input v-model="data.default" size="medium" placeholder="默认值"  style="width: 565px;margin: 5px 5px 5px 20px;" />
          </div>
          <div  v-for="(data, index) in this.formulaVariableData" >
            <span >{{ data.name }}：</span>
            <el-input v-model="data.min" size="medium" placeholder="最小值"  style="width: 255px;margin: 5px 20px 5px 20px;" />
            <span  > ~ </span>
            <el-input v-model="data.max" size="medium" placeholder="最大值" style="width: 255px;margin: 5px 20px 5px 20px;" />
          </div>
        </el-form-item>

        <el-form-item label="是否必填" v-if="this.form.formTypeName !== 'datalist'">
          <el-select v-model="form.jsRequired" placeholder="请选择是否必填" style="width: 80%;">
            <el-option
              v-for="dict in dict.type.logic_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="查看方式" v-if="this.form.formTypeName === 'datalist'">
          <el-radio v-model="form.viewType" label="0">列表显示</el-radio>
          <el-radio v-model="form.viewType" label="1">弹窗显示</el-radio>
          <el-radio v-model="form.viewType" label="2">绘图显示</el-radio>
        </el-form-item>
        <el-form-item label="是否可增删" v-if="this.form.formTypeName === 'datalist'">
          <el-select v-model="form.isAddDelFlag" placeholder="请选择是否可增删" style="width: 80%;">
            <el-option
              v-for="dict in dict.type.logic_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否只读(来自addComplex)" v-if="this.form.formTypeName !== 'datalist'">
          <el-select v-model="form.isReadOnly" placeholder="请选择是否只读" style="width: 80%;">
            <el-option
              v-for="dict in dict.type.logic_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="详情中是否显示" v-if="this.form.formTypeName !== 'datalist'">
          <el-select v-model="form.isShow" placeholder="请选择详情中是否显示" style="width: 80%;">
            <el-option
              v-for="dict in dict.type.logic_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上传类型" v-if="this.form.formTypeName == 'upload'">
          <el-select v-model="form.uploadtypeId" placeholder="请选择上传类型" style="width: 80%;">
            <el-option
              v-for="upload in uploadTypeList"
              :key="upload.id"
              :label="upload.name"
              :value="upload.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选项值(逗号分割)" v-if="this.form.formTypeName !== 'datalist'">
          <el-input v-model="form.defaultValue" placeholder="请输入选项值(逗号分割)" style="width: 80%;"/>
        </el-form-item>
        <el-form-item label="排序" >
          <el-input v-model="form.sortNum" placeholder="请输入排序" style="width: 80%;"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>
    <edit-complex ref="editComplex" @getList="getList"/>
    <select-field ref="selectField" @getList="getList"/>

  </div>
</template>

<script>
import {
  listField,
  getField,
  delField,
  addField,
  updateField,
  basicCodeValid,
  getCodeSortNum,
  getAttributes,
  linkList,
  listRefField
} from "@/api/form/field";
import { listType as uploadTypeList } from "@/api/form/uploadtype";
import editComplex from "./editComplex";
import selectField from "@/views/form/config/model/selectfield.vue";

export default {
  name: "attributeAdd",
  components: {selectField, editComplex},
  dicts: ['basic_java_type', 'form_type_name', 'data_extend', 'logic_yes_no', 'field_type', 'col_cal_type'],
  data() {
    var ValidCode = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('代码不能为空'));
      } else {
        basicCodeValid(value, this.id).then(data => {
          if (data == '1') {
            callback(new Error('已经存在该代码'));
          } else {
            callback();
          }
        });
      }
    };
    return {
      id: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      fieldList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      dictList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        modelId: null,
        basicCode: null,
        basicName: null,
        dataExtend: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        basicName: [
          { required: true, trigger: "blur", message: "名称不能为空" }
        ],basicCode: [
          { validator: ValidCode, trigger: "blur"}
        ],
      },
      uploadTypeList: [],
      selectList: [],
      colCalFieldIds: [],
      componentList: [],
      drawTypeList: [],
      formulaList: [],
      simpleList: [],
      complexList: [],
      formulaArgumentData: [], //公式参数数据
      formulaVariableData: [], //公式变量数据
      argumentQueryParams: {},
    };
  },
  created() {
    this.getList();
    uploadTypeList().then(data => {
      this.uploadTypeList = data;
    });
    //绘图类型 drawTypeList
    let query = {};
    query.formulaOrDraw = '1';
    //函数公式 formulaList
    let formulaQuery = {};
    formulaQuery.formulaOrDraw = '0';
  },
  methods: {
    chDataExtend(val) {
      this.form.basicJavaType = '';
      this.form.formDictType = '';
      this.$set(this.form, 'componentIds', []);
      this.componentList = [];
      this.form.personNum = undefined;
      if (val === 'datalist') {
        this.form.dataExtend = 'true';
        this.form.jsRequired = null;
        this.form.isReadOnly = null;
        this.form.isShow = null;
        this.form.isAddDelFlag = '1';
        if (this.complexList != null && this.complexList.length > 0) {
          this.componentList = this.complexList;
        }
      } else if (val !== 'datalist') {
        this.form.dataExtend = 'false';
        this.form.jsRequired = '0';
        this.form.isReadOnly = '0';
        this.form.isShow = '1';
        this.form.isAddDelFlag = null;
        if (this.simpleList != null && this.simpleList.length > 0) {
          this.componentList = this.simpleList;
        }
      } else {
        if (this.simpleList != null && this.simpleList.length > 0) {
          this.componentList = this.simpleList;
        }
      }
    },
    chFormulaData(id,formulaId){
      //根据公式id查询出参数列表， 分类设置到  formulaArgumentData: [], formulaVariableData: []
      this.formulaVariableData = [];
      this.formulaArgumentData = [];
      if (formulaId === null || formulaId === undefined || formulaId === ''){
        return;
      }
      if (id === null || id === undefined){
        this.argumentQueryParams.parentId = formulaId+"";
      }else {
        getField(id).then(response => {
          if (response.data.drawTypeId === formulaId){
            if (response.data.drawArgumentData !== '' && response.data.drawArgumentData !== null ){
              let dataList = JSON.parse(this.form.drawArgumentData);
              dataList.forEach((argument)=>{
                if (argument.type === '0'){
                  this.formulaVariableData.push(argument);
                }else if (argument.type === '1'){
                  this.formulaArgumentData.push(argument);
                }
              });
            }
          }else {
            this.argumentQueryParams.parentId = formulaId+"";
          }
        });
      }
    },
    getList() {
      this.$emit("getList");
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset(basicCode, sortNum) {
      this.form = {
        id: null,
        createTime: null,
        createUser: null,
        delFlag: null,
        remarks: null,
        sortNum: sortNum,
        updateTime: null,
        updateUser: null,
        hierarchy: null,
        parentId: null,
        parentIds: null,
        basicCode: basicCode,
        basicColType: null,
        basicFormula: null,
        basicJavaType: '',
        basicLength: null,
        basicName: null,
        dataExtend: 'false',
        dataGenStratgy: null,
        dataUnit: null,
        formDictType: '',
        formTypeName: 'input',
        defaultValue: null,
        formwidth: null,
        viewType: '',
        isShow: '1',
        jsMatchWhat: null,
        jsRequired: '0',
        modelId: null,
        uploadtypeId: null,
        rowspan: null,
        frontGridId: null,
        displayNumber: null,
        isOnly: null,
        isReadOnly: '0',
        initData: null,
        isAddDelFlag: '1',
        isHighLight: null,
        imgid: null,
        parentLinkageId: '',
        attributeType: '0',
        componentId: '',
        componentIds: [],
        drawTypeId: '',
        personNum: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd(modelId) {
      this.queryParams.modelId = modelId;
      this.id = '';
      getCodeSortNum().then(data => {
        let dataArr = data.split(':');
        getAttributes().then(dictList => {
          if (dictList != null) {
            this.dictList = dictList;
          }
          this.reset(dataArr[0], dataArr[1]);
          linkList().then(data => {
            this.selectList = data;
            this.open = true;
            this.title = "添加";
          });
        });
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      if (this.form.formTypeName === 'datalist'){
        this.form.dataExtend ='true';
      }else {
        this.form.dataExtend ='false';
      }
      const id = row.id || this.ids
      this.id = id;
      getField(id).then(response => {
        getAttributes().then(dictList => {
          if (dictList != null) {
            this.dictList = dictList;
          }
          this.form = response.data;
          if (this.form.personNum == null) {
            this.form.personNum = undefined;
          }
          if (this.form.dataExtend == 'true') {//复杂属性
            this.componentList = this.complexList;
          } else {
            this.componentList = this.simpleList;
          }
          this.formulaVariableData = [];
          this.formulaArgumentData = [];
          if (this.form.drawArgumentData !== '' && this.form.drawArgumentData !== null ){
            let dataList = JSON.parse(this.form.drawArgumentData);
            dataList.forEach((argument)=>{
              if (argument.type === '0'){
                this.formulaVariableData.push(argument);
              }else if (argument.type === '1'){
                this.formulaArgumentData.push(argument);
              }
            });
          }
          linkList(id).then(data => {
            this.selectList = data;
            this.open = true;
            this.title = "修改";
          });
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.loading = true;
          console.log('valid', valid);

          if (!(this.form.componentIds != null && this.form.componentIds.length > 0)) {
            this.form.personNum = undefined;
          }
          if (this.form.formTypeName != 'upload') {
            this.form.uploadtypeId = '';
          }
          if (this.formulaArgumentData.length > 0 || this.formulaVariableData.length > 0){
            let formulaDataList = [];
            this.formulaArgumentData.forEach((argument)=>{
              formulaDataList.push(argument);
            });
            this.formulaVariableData.forEach((variable)=>{
              formulaDataList.push(variable);
            });
            let json = JSON.stringify(formulaDataList);
            this.form.drawArgumentData = json;
          }
          console.log(2);

          if (this.form.id != null) {
            updateField(this.form).then(response => {
              console.log('response', response);

              if (response.code === 200){
                this.open = false;
                this.$modal.msgSuccess("修改成功");
                this.getList();
                this.loading = false;
              }
            }).catch(error=>{
              console.log(error);
              this.loading = false;
            });
          } else {
            addField(this.form).then(response => {
              if (response.code === 200){
                this.open = false;
                if (this.queryParams.modelId != null){
                  this.$refs.selectField.submitForm(response.data,this.queryParams.modelId);
                  this.loading = false;
                }else {
                  this.$modal.msgSuccess(response.msg);
                  this.getList();
                  this.loading = false;
                }
              }
            }).catch(error=>{
              console.log(error);
              this.loading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除数据项？').then(function() {
        return delField(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/field/export', {
        ...this.queryParams
      }, `field_${new Date().getTime()}.xlsx`)
    },
    editComplex(row) {
      this.$refs.editComplex.showDialog(row)
    }
  }
};
</script>
